package org.viettan.android.main.activities.campaign;

import java.util.List;

import org.viettan.android.main.activities.common.ArticleListActivity;
import org.viettan.android.main.intents.IntentKeys;
import org.viettan.android.main.io.EntityRetrievalException;
import org.viettan.android.main.managers.ArticleManager;
import org.viettan.android.main.model.Article;

import android.util.Pair;

import com.google.common.collect.Lists;
import com.google.inject.Inject;

/**
 * Displays articles that belong in the given campaign.
 */
public class CampaignActivity extends ArticleListActivity {
    @Inject
    private ArticleManager articleManager;

    @Override
    protected List<Article> getArticles(boolean useCache) throws EntityRetrievalException {
	int campaignId = getIntent().getIntExtra(IntentKeys.CAMPAIGN_ID.name(), 0);
	Pair<List<Article>, List<Article>> bothArticleSet = articleManager.getCampaignArticles(
		campaignId, useCache);

	List<Article> allArticles = Lists.newArrayList();

	// Okay, this is stupid. The main articles is always a list
	// of two items: the first one pointing back to the campaign (useless). The second
	// one is the interesting what-you-can-do articles, so might as well deep-load
	// that list too and display it here
	for (Article mainArticle : bothArticleSet.first) {
	    int sectionId = mainArticle.getSectionId();
	    if (sectionId == 0 || sectionId == campaignId) {
		// the first section always seems to be referencing itself so let's skip
		continue;
	    }

	    // HACK: So, the ArticleListActivity is designed to display a single
	    // list of articles, and therefore all the parameters operate only on
	    // List<Article>. This campaign activity is different though as it displays
	    // two lists of articles. We are going to use the related articles
	    // list to pass around in the generally ArticleListActivity framework, and
	    // "leak" the other articles over to be displayed:
	    // sectionTitle = mainArticle.getTitle();
	    allArticles.addAll(articleManager.getArticlesInSection(mainArticle.getSectionId(),
		    useCache));

	    // let's skip any other main articles (never encountered more than two so far)
	    break;
	}

	allArticles.addAll(bothArticleSet.second);
	return allArticles;
    }
}
